<template>
    <div>
        <div style="margin-bottom: 20px;">
            <el-input v-model="searchQuery" placeholder="关键词搜索" style="width: 300px; margin-right: 10px;" />
            <el-button type="primary" @click="fetchKsData">查询</el-button>
        </div>

        <el-table :data="paginatedData" border @selection-change="handleKsSelectionChange"
            style="height: 400px; width: 100%; overflow: auto;">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="cj_code" label="生产车间编码" />
            <el-table-column prop="cj_name" label="生产车间名称" />
            <el-table-column prop="gc_name" label="所属工厂" />
            <el-table-column prop="cj_remark" label="备注" />
        </el-table>

        <div style="margin-top: 10px; text-align: right;">
            <el-button type="default" @click="resetSelection">反选</el-button>
        </div>

        <div style="margin-top: 20px; text-align: center;">
            <span>共 {{ totalItems }} 条，当前第 {{ currentPage }} 页</span>
            <el-pagination @current-change="handlePageChange" :current-page="currentPage" :page-size="pageSize"
                :total="totalItems" layout="total, prev, pager, next, jumper" />
        </div>

        <div style="margin-top: 20px;">
            <el-button type="success" @click="cancelSelection">取消</el-button>
            <el-button type="success" style="margin-left: 10px;" @click="confirmSelection">确认</el-button>
        </div>
    </div>
</template>

<script>
import { ref, computed } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

export default {
    setup(props, { emit }) {
        const ksTableData = ref([]);
        const selectedIds = ref([]);
        const searchQuery = ref('');
        const currentPage = ref(1);
        const pageSize = ref(5);
        const totalItems = ref(0);
        const selectedRows = ref([]);

        // 获取产品数据  
        const fetchKsData = () => {
            axios.get('/api/GC/GetCJbyCode')
                .then((response) => {
                    ksTableData.value = response.data || [];
                    totalItems.value = ksTableData.value.length; // 更新总条数  
                })
                .catch((error) => {
                    console.error('获取产品数据失败', error);
                    ElMessage.error('加载产品数据失败，请稍后再试');
                });
        };

        // 处理表格选中变化  
        const handleKsSelectionChange = (val) => {
            console.log(val)
            selectedRows.value = val.length > 0 ? [val[0]] : [];
        };

        // 过滤和分页数据  
        const paginatedData = computed(() => {
            const filteredData = ksTableData.value.filter(item => {
                const searchTerm = searchQuery.value.toLowerCase();
                return item.cj_code.toLowerCase().includes(searchTerm) ||
                    item.cj_name.toLowerCase().includes(searchTerm) ||
                    item.gc_name.toLowerCase().includes(searchTerm) ||
                    item.cj_remark.toLowerCase().includes(searchTerm);
            });

            const start = (currentPage.value - 1) * pageSize.value;
            return filteredData.slice(start, start + pageSize.value);
        });

        const resetSelection = () => {
            const allIds = paginatedData.value.map(item => item.cj_code);
            selectedIds.value = allIds.filter(id => !selectedIds.value.includes(id));
        };

        const confirmSelection = () => {
            if (selectedRows.value.length === 0) {
                console.log('没有选中任何行');
                return;
            }
            const firstSelectedRow = selectedRows.value[0];
            const selectedData = {
                id: firstSelectedRow.cj_code,
                name: firstSelectedRow.cj_name
            };
            emit('selection-confirmed', selectedData);
        };

        const cancelSelection = () => {
            emit('cancel-selection');
        };

        const handlePageChange = (page) => {
            currentPage.value = page;
        };

        fetchKsData();

        return {
            handleKsSelectionChange,
            ksTableData,
            selectedIds,
            searchQuery,
            paginatedData,
            resetSelection,
            confirmSelection,
            cancelSelection,
            currentPage,
            pageSize,
            totalItems,
            handlePageChange,
            selectedRows
        };
    }
};  
</script>

<style scoped>
/* 添加适当的样式以匹配设计 */
</style>